//
//  PPAlbumEditContentViewController.m
//  pickpic
//
//  Created by 胡文广 on 2017/5/19.
//  Copyright © 2017年 MicroDream. All rights reserved.
//

#import "PPAlbumEditContentViewController.h"
#import "PPAlbumEditTitleCell.h"
#import "PPAlbumPictureCell.h"
#import "PPAlbumSortCell.h"

#import "PPAlbumContentPrivacyViewController.h"
#import "PPAlbumContentOrderViewController.h"
#import "PPAlbumContentCommentPermissionViewController.h"
#import "PPAlbumContentTagsViewController.h"
#import "PPAssetsPickerViewController.h"
#import "PPAlbumContentPictureViewController.h"

#import "PPAlbumContentTableViewPictureRowCell.h"
#import "PPAlbumContentTableViewPictureAddCell.h"
#import "PPAlbumContentTableViewTitleCell.h"
#import "PPAlbumContentTableViewDescriptionCell.h"

#import "PPAlbumContentViewDataSource.h"

#import "PPAlbumModel.h"

#import "PPAlbumManager.h"

#import "PPImageTransaction.h"
#define kRows 4

#define kAlbumTitleFont ([UIFont fontWithName:@"Helvetica-Bold" size:24])
#define kAlbumDescFont ([UIFont systemFontOfSize:18])
#define kAlbumTitleHeight 70
#define kAlbumDescSpace 10  
@interface PPAlbumEditContentViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate, PPAlbumContentPictureViewControllerDelegate,TZImagePickerControllerDelegate,PPAlbumPictureCellDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (readwrite, nonatomic, strong) PPAlbumContentViewDataSource *dataSource;

@property (nonatomic,assign) CGFloat titleCellHeight;
@property (nonatomic,assign) CGFloat descCellHeight;
@property (nonatomic,assign) CGFloat picCellHeight;
@property (nonatomic,assign) CGFloat sortCellHeight;


@property (nonatomic,copy) NSString *albumTitle;
@property (nonatomic,copy) NSString *albumDesc;

@property (nonatomic,strong) NSMutableArray *pictures;

@property (nonatomic,assign) BOOL isSort;
@property (nonatomic,assign) CGFloat keboardHeight;
@property (nonatomic,assign) NSTimeInterval animalInterval;

@property (nonatomic,assign) BOOL isCover;
@property (nonatomic,copy) NSString *tempTitle;
@end

@implementation PPAlbumEditContentViewController

static NSString *const editCellID = @"AlbumEditTitleCell";
static NSString *const picCellID = @"AlbumPictureCell";
static NSString *const sortCellID = @"AlbumSortCell";
- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
}
- (NSMutableArray *)pictures{

    if (!_pictures) {
        
        _pictures = [NSMutableArray array];
    }
    return _pictures;
}
- (void)loadView{

    _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = WHITE;
    self.view = _tableView;
}
- (void)cancelOperation{

    DGBlockAlertView *alertView = [DGBlockAlertView alertWithTitle:@"是否退出编辑？" message:nil cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"退出" comfirmBlock:^{
        [self popViewPreviousController];
    }];
    
    [alertView show];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.keboardHeight = 0;
    self.picCellHeight = 144;
    self.sortCellHeight = 60;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = WHITE;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 14, 0, 0);
    
    self.tableView.tableFooterView = [[UIView alloc] init];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelOperation)];

    
    
    
    if (IS_IOS_8) {
            [self.navigationItem.leftBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PFFontMedium(16)} forState:UIControlStateNormal];
    }else{
    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PPFONT(PFBold, 16)} forState:UIControlStateNormal];
    }
    
    self.navigationItem.leftBarButtonItem.tintColor = BLACK;

    
    if (IS_IOS_8) {
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:PFFontMedium(16),NSForegroundColorAttributeName:BLACK}];
    }else{
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:PPFONT(PFBold, 17),NSForegroundColorAttributeName:BLACK}];
    }
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveAlbumInfo)];
    self.navigationItem.rightBarButtonItem.tintColor = COLORA(0, 118, 255);
    
    if (IS_IOS_8) {
            [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PFFontMedium(16)} forState:UIControlStateNormal];
    }else{
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PPFONT(PFBold, 16)} forState:UIControlStateNormal];
    }
    


    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PPAlbumEditTitleCell class]) bundle:nil] forCellReuseIdentifier:editCellID];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PPAlbumSortCell class]) bundle:nil] forCellReuseIdentifier:sortCellID];
    [self.tableView registerClass:[PPAlbumPictureCell class] forCellReuseIdentifier:picCellID];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
     
                                                 name:UIKeyboardWillShowNotification
     
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self
     
                                            selector:@selector(keyboardWillHide:)
     
                                                name:UIKeyboardDidHideNotification
     
                                              object:nil];
    
    
    if(_auuid != nil) {
        NSArray <PPAlbumImageModel *> *images = [PPAlbumImageModel where:@{@"auuid": _auuid, @"deleted": @(NO)}];
        if (images.count == 0) {
            PPLog(@"空相册");
            self.isCover = YES;
        }
        
    }
    
}
#pragma mark -获取相册
- (void)setImages:(NSArray *)images{

    _images = images;
    
    _dataSource = [[PPAlbumContentViewDataSource alloc] init];
    _dataSource.privacy = @(PPAlbumPrivacyAll);
    _dataSource.permission = @(PPAlbumCommentEnabled);
    _dataSource.order = @(PPAlbumOrderDesc);
    if (self.images.count > 0) {
        for (UIImage *img in self.images) {
            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
            artwork.uuid = [NSString uuid];
            artwork.image = [img fixOrientation];
            artwork.created = YES;
            [self.dataSource.images addObject:artwork];
            [self.dataSource.insertedImages addObject:artwork];
             [self.pictures addObject:artwork];
        }
    }
    PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
    artwork.image = [UIImage imageNamed:@"pic_add"];
    artwork.isFlag =TRUE;
    if(self.dataSource.order.integerValue == PPAlbumOrderAsc) {
//        [self.dataSource.images insertObject:artwork atIndex:0];
        [self.pictures insertObject:artwork atIndex:0];
    } else {
//        [self.dataSource.images addObject:artwork];
         [self.pictures addObject:artwork];
    }
    
//    for (PPAbstractArtwork *art in self.dataSource.images) {
//        [self.pictures addObject:art];
//    }
    
    self.isSort = [_dataSource.order integerValue];
    [self.tableView reloadData];
    
    
    
    
    
//    if (self.images.count > 0) {
//        for (UIImage *img in self.images) {
//            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
//            artwork.uuid = [NSString uuid];
//            artwork.image = [img fixOrientation];
//            artwork.created = YES;
////            [self.dataSource.images addObject:artwork];
////            [self.dataSource.insertedImages addObject:artwork];
//            [self.pictures addObject:artwork];
//        }
//    }
//    PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
//    artwork.image = [UIImage imageNamed:@"pic_add"];
//    artwork.isFlag =TRUE;
//    if(self.dataSource.order.integerValue == PPAlbumOrderAsc) {
//        [self.pictures insertObject:artwork atIndex:0];
//    } else {
//        [self.pictures addObject:artwork];
//    }
//    
////    self.pictures = _dataSource.images;
//    self.isSort = [_dataSource.order integerValue];
//    [self.tableView reloadData];
    
}
- (void)saveAlbumInfo{
    
    
    if ([PPNetworkManager sharedInstance].networkStatus == PPNetStatusNotReachable) {
        
         [self.navigationController.view toastMessage:@"当前网络不可用，请检查您的网络设置"];
        return;
    }
    
    [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
    
    NSIndexPath *titleIndex = [NSIndexPath indexPathForRow:0 inSection:0];

    PPAlbumEditTitleCell *titleCell = (PPAlbumEditTitleCell *)[self.tableView cellForRowAtIndexPath:titleIndex];
    
    self.albumTitle = titleCell.titleTextView.text;
    
    if(self.albumTitle.charCount > 16) {
        [self.navigationController.view toastMessage:@"相册名称不能超过16个字符"];
        return;
    }
    
    NSIndexPath *descIndex = [NSIndexPath indexPathForRow:1 inSection:0];
    PPAlbumEditTitleCell *descCell = [self.tableView cellForRowAtIndexPath:descIndex];
    self.albumDesc = descCell.titleTextView.text;
    
    if(self.albumDesc.length > 200) {
        [self.navigationController.view toastMessage:@"相册描述不能超过200个字符"];
        return;
    }
    
    if(self.albumTitle.length == 0) {
        self.albumTitle = @"未命名图册";
    }
    
    
    _dataSource.title = self.albumTitle;
    _dataSource.desc = self.albumDesc;
    
//    if (self.dataSource.images.count >0) {
//        [self.dataSource.images removeAllObjects];
//    }
//    
//    if (self.dataSource.insertedImages.count >0) {
//        [self.dataSource.insertedImages removeAllObjects];
//    }
//    
//    for (PPAbstractArtwork *artwork in self.pictures) {
//        if (artwork.uuid) {
//            [self.dataSource.images addObject:artwork];
//            [self.dataSource.insertedImages addObject:artwork];
//            
//        }
//    }
//    
//    if(_dataSource.order.integerValue == PPAlbumOrderAsc) {
//        
////        [self.dataSource.images removeLastObject];
//        [self.pictures removeLastObject];
//    } else {
////        [self.dataSource.images removeObjectAtIndex:0];
//        [self.pictures removeObjectAtIndex:0];
//    }
//    
    
    
    if (self.pictures.count <=1 ) {
        //代表没有图片 删除电子书 和 相册所有图片
        if ([PPAlbumModel existingAlbumForUUID:_auuid].albumID) {
            [PPNetworkService deleteAlbumeBookWithAlbumID:[PPAlbumModel existingAlbumForUUID:_auuid].albumID callback:^(id data, NSError *error) {
                
            }];
        }
    }
    
    NSString *coverUUID = nil;
    
    if(_dataSource.coverUUID != nil) {
        coverUUID = _dataSource.coverUUID;
    } else {
        // 从images里找第一张图作为cover
        BOOL force = NO;
        if(_auuid != nil) {
            PPAlbumModel *album = [PPAlbumModel find:@{@"auuid": _auuid}];
            if(album.coverKey.length == 0 || album.coverHost.length == 0) {
                force = YES;
            }
            
        } else {
            force = YES;
        }
        
        if(force || self.isCover) {
            NSArray <PPAbstractArtwork *> *sortedImages = nil;
//            if(_dataSource.order.integerValue == PPAlbumOrderAsc) {
//                sortedImages = [self.dataSource.images.reverseObjectEnumerator allObjects];
//            } else {
                sortedImages = self.dataSource.images;
//            }
            coverUUID = sortedImages.firstObject.uuid;
  
        }
    }

    
    if(_type == PPAlbumEditContentViewControllerTypeCreate) {
        [[PPAlbumManager sharedInstance] offlineCreateAlbumWithArtworks:_dataSource.insertedImages tags:_dataSource.tags title:_dataSource.title description:_dataSource.desc order:_dataSource.order permission:_dataSource.permission privacy:_dataSource.privacy privacyUserIDs:_dataSource.privacyUserIDs coverUUID:coverUUID];
    } else {
        [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:_auuid insertedArtworks:_dataSource.insertedImages modifiedArtworks:_dataSource.modifiedImages deletedArtworks:_dataSource.deletedImages tags:_dataSource.tags title:_dataSource.title description:_dataSource.desc order:_dataSource.order permission:_dataSource.permission privacy:_dataSource.privacy privacyUserIDs:_dataSource.privacyUserIDs coverUUID:coverUUID];
    }
    
//    if (self.pictures.count <=1 ) {
//        NSDictionary *Dict = @{
//                               @"pageInfo":@{@"page":@"1",@"rows":@"100"},
//                               @"albumId":[PPAlbumModel existingAlbumForUUID:_auuid].albumID,
//                               };
//        [PPNetworkService queryAlbumPictureids:Dict callback:^(id data, NSError *error) {
//            if (!error) {
//                
//                NSMutableArray *picIds = [NSMutableArray array];
//                for (NSDictionary *picDic in data[@"rows"]) {
//                    [picIds addObject:picDic[@"pictureId"]];
//                }
//                
//                
//                [PPNetworkService deletePictureFromAlbum:[PPAlbumModel existingAlbumForUUID:_auuid].albumID pictures:[picIds copy] callback:^(id data, NSError *error) {
//                    if(error == nil) {
//                        [[NSManagedObjectContext threadObjectContext] saveContext];
//                    }
//                    
//                }];
//            }
//        }];
//    }
    
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return kRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
        {
            PPAlbumEditTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:editCellID];
                cell.titleTextView.textContainerInset = UIEdgeInsetsMake(21, 0, 21, 0);
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.titleTextView.delegate = self;
            cell.titleTextView.font = kAlbumTitleFont;
            cell.titleTextView.textColor = [UIColor colorWithHexString:@"#000000"];
            
            cell.placeholderLabel.font = kAlbumTitleFont;
            cell.placeholderLabel.text = @"标题";
//            cell.placeholderLabel.hidden = _dataSource.title.length;
            cell.placeholderLabel.hidden = self.albumTitle.length;
            cell.titleTextView.text = self.albumTitle;
            
            cell.titleTextView.tag = indexPath.row;
            return cell;
        }
            break;
        case 1:{
            PPAlbumEditTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:editCellID];
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
             cell.titleTextView.textContainerInset = UIEdgeInsetsMake(28, 0, 28, 0);
            cell.placeholderLabel.font = kAlbumDescFont;
            cell.titleTextView.font = kAlbumDescFont;
            cell.placeholderLabel.hidden = _dataSource.desc.length;
             cell.placeholderLabel.text = @"描述";
            
            cell.titleTextView.textColor = [UIColor colorWithHexString:@"#333333"];
//            cell.titleTextView.text = self.albumDesc;
            
            if (self.albumDesc.length > 0) {
                
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.lineSpacing = kAlbumDescSpace/2;// 字体的行间距
                
                NSDictionary *attributes = @{
                                             NSFontAttributeName:cell.titleTextView.font,
                                             NSParagraphStyleAttributeName:paragraphStyle
                                             };
                cell.titleTextView.attributedText = [[NSAttributedString alloc] initWithString:self.albumDesc attributes:attributes];
            }
            
            cell.titleTextView.delegate = self;
            cell.titleTextView.tag = indexPath.row;
            return cell;
            
        }
            break;
        case 2:{
            PPAlbumPictureCell *cell = [tableView dequeueReusableCellWithIdentifier:picCellID];
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
//            NSMutableArray *sortedImages = nil;
            cell.delegate = self;
//            if(_dataSource.order.integerValue == PPAlbumOrderAsc) {
//                sortedImages = self.dataSource.images;
//            } else {
//                sortedImages = [[self.dataSource.images.reverseObjectEnumerator allObjects] copy];
//            }
            cell.pictures = self.pictures;
            return cell;
            
        }
            break;
        case 3:{
            PPAlbumSortCell *cell = [tableView dequeueReusableCellWithIdentifier:sortCellID];
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.dataSource = self.dataSource;
            return cell;
            
        }
            break;
            
        default:
            break;
    }
    
    return [[UITableViewCell alloc] init];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 3) { 
        PPAlbumContentOrderViewController *orderViewController = [[PPAlbumContentOrderViewController alloc] init];
        orderViewController.dataSource = _dataSource;
        orderViewController.BlockFinsh = ^(NSInteger order){

            if (order != self.isSort) {
                self.pictures = [[self.pictures.reverseObjectEnumerator allObjects] mutableCopy];
                self.isSort = order;
                
            }

            NSIndexPath *picIndex = [NSIndexPath indexPathForRow:2 inSection:0];
            NSIndexPath *sortIndex = [NSIndexPath indexPathForRow:3 inSection:0];
            [self.tableView reloadRowsAtIndexPaths:@[picIndex,sortIndex] withRowAnimation:UITableViewRowAnimationNone];
        
        };
        [self.navigationController pushViewController:orderViewController animated:YES];
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    switch (indexPath.row) {
        case 0:
            return _titleCellHeight <= 0?kAlbumTitleHeight:_titleCellHeight;
            break;
        case 1:
            return _descCellHeight<= 0?kAlbumTitleHeight:_descCellHeight;
            break;
        case 2:
            return self.picCellHeight = [self justFrame] + 32*2;
            break;
        case 3:
            return _sortCellHeight;
            break;
            
        default:
            break;
    }
    
    return 44;

}
//#define itemW 80 //每个小视图高80
//#define itemH 80 //每个小视图宽80
#define kColCount 4 //每行视图数量一定，都是4个
- (CGFloat )justFrame{
        CGFloat marginY = 9;//高度
        CGFloat itemH = (SCREEN_WIDTH -14*2 - 3*marginY)/4;
        //行号  这里多出一张 "+"号图 所有+1
        NSInteger row = (self.pictures.count -1)/kColCount;

        return  marginY + row * (itemH + marginY) + itemH - marginY;
}

- (float) heightForString:(UITextView *)textView andWidth:(float)width{
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.height;
}
#pragma mark -textViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView{
    NSIndexPath *indexP = [NSIndexPath indexPathForRow:textView.tag inSection:0];
    PPAlbumEditTitleCell *cell = [self.tableView cellForRowAtIndexPath:indexP];
    cell.placeholderLabel.textColor = BLACK;
    cell.placeholderLabel.hidden = textView.text.length;
    if (textView.tag == 0) {
        self.albumTitle = textView.text;
    }else if (textView.tag ==1){
        self.albumDesc = textView.text;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (textView.tag == 0) {
        if(textView.text.charCount > 16) {
            [self.navigationController.view toastMessage:@"相册名称不能超过16个字符"];
//             return NO;
        }
    }else if (textView.tag ==1){
        if(textView.text.length > 200) {
            [self.navigationController.view toastMessage:@"相册描述不能超过200个字符"];
//            return NO;
        }
    }
    if ([text isEqualToString:@"\n"]){
      
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
//        return NO; //这里返回NO，就代表return键值失效，
    
    }
    
    return YES;
    
}
- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    NSIndexPath *indexP = [NSIndexPath indexPathForRow:textView.tag inSection:0];
    PPAlbumEditTitleCell *cell = [self.tableView cellForRowAtIndexPath:indexP];
    cell.placeholderLabel.textColor = COLORA(242, 242, 242);
    cell.placeholderLabel.hidden = textView.text.length;
    //防止输入时在中文后输入英文过长直接中文和英文换行
//    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
//    
//    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
//    NSDictionary *attributes = @{
//                                 NSFontAttributeName:textView.font,
//                                 NSParagraphStyleAttributeName:paragraphStyle
//                                 };
//    
//    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
    
    
    if (textView.tag == 1) {
//        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//        paragraphStyle.lineSpacing = 14;// 字体的行间距
//        
//        NSDictionary *attributes = @{
//                                     NSFontAttributeName:textView.font,
//                                     NSParagraphStyleAttributeName:paragraphStyle
//                                     };
//      textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
        
        [self textViewparagraphStyle:textView withText:textView.text];
        
        
        if (self.keboardHeight > 0 && cell.frame.origin.y + self.descCellHeight> self.keboardHeight) {
            
            
            self.tableView.contentOffset = CGPointMake(0, (cell.frame.origin.y + self.descCellHeight - self.keboardHeight));
            
//            [UIView animateWithDuration:self.animalInterval animations:^{
            
//                CGRect viewF = self.tableView.frame;
//                viewF.origin.y = -(cell.frame.origin.y + self.descCellHeight - self.keboardHeight);
//                self.tableView.frame = viewF;
//            }];
            
        }
        
        
    }
    
    
    
    
}
- (void)textViewDidChange:(UITextView *)textView{
    NSIndexPath *indexP = [NSIndexPath indexPathForRow:textView.tag inSection:0];
    PPAlbumEditTitleCell *cell = [self.tableView cellForRowAtIndexPath:indexP];
    cell.placeholderLabel.hidden = textView.text.length;
//    cell.titleTextView.text = textView.text;
//
//    CGSize size = [textView sizeThatFits:textView.contentSize];
    
    CGSize size = textView.contentSize;
    if (textView.tag == 0) {
        
        CGRect f = cell.frame;
        f.size.height = size.height;
        cell.frame = f;
        
        CGRect textF = textView.frame;
        textF.size.height = size.height+21;
        textView.frame = textF;
        self.titleCellHeight = size.height;
        

    }else if (textView.tag ==1){
        
        
        CGRect f = cell.frame;
        f.size.height = size.height;
        cell.frame = f;
        
        CGRect textF = textView.frame;
        textF.size.height = size.height;
        textView.frame = textF;
        
        self.descCellHeight = size.height;
        
        
        if (self.keboardHeight > 0 && cell.frame.origin.y + self.descCellHeight+14 > self.keboardHeight) {
              self.tableView.contentOffset = CGPointMake(0, (cell.frame.origin.y + self.descCellHeight - self.keboardHeight));
//            [UIView animateWithDuration:self.animalInterval animations:^{
//                CGRect viewF = self.tableView.frame;
//                viewF.origin.y = - (cell.frame.origin.y + self.descCellHeight - self.keboardHeight);
//                self.tableView.frame = viewF;
//                
//            }];
        }
        

    }

//    CGFloat temp = CGRectGetMaxY(cell.frame);
//    
//    if (textView.tag == 0) {
//        temp = temp + self.descCellHeight;
//    }
    
    
    for (int i = 0; i<kRows; i++) {
        
        if (indexP.row < i) {
            
            UITableViewCell *tempCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            
            if ([tempCell isKindOfClass:[PPAlbumPictureCell class]]) {
                PPAlbumPictureCell *picCell = (PPAlbumPictureCell *)tempCell;
                PPAlbumPictureCell *descCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
                CGRect cellF = picCell.frame;
                cellF.origin.y = CGRectGetMaxY(descCell.frame);
                picCell.frame =cellF;
                
                
            }else if([tempCell isKindOfClass:[PPAlbumSortCell class]]){
            
                PPAlbumPictureCell *picCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];

                PPAlbumSortCell *sortCell = (PPAlbumSortCell *)tempCell;
                CGRect sortCellF = sortCell.frame;
                sortCellF.origin.y = CGRectGetMaxY(picCell.frame);
                sortCell.frame =sortCellF;
            
            }else if([tempCell isKindOfClass:[PPAlbumEditTitleCell class]] &&textView.tag == 0 ){
                
                PPAlbumEditTitleCell *descCell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
                CGRect descF = descCell.frame;
                descF.origin.y = self.titleCellHeight;
                descCell.frame =descF;
            }
        }
    }
    
}


#pragma mark -albumdata

- (void)setAuuid:(NSString *)auuid {
    _auuid = auuid;
    
    if(auuid == nil) {
        return;
    }
    
    
    if (!_dataSource) {
        
        _dataSource = [[PPAlbumContentViewDataSource alloc] init];
        _dataSource.privacy = @(PPAlbumPrivacyAll);
        _dataSource.permission = @(PPAlbumCommentEnabled);
        _dataSource.order = @(PPAlbumOrderDesc);
    }
    
    
    PPAlbumModel *album = [PPAlbumModel find:@{@"auuid" : auuid}];
    
    _dataSource.title = album.title;
    _dataSource.desc = album.desc;
    _dataSource.privacy = album.privacy;
    _dataSource.permission = album.permission;
    _dataSource.order = album.order;
    
    self.albumTitle = _dataSource.title;
    UITextView *titleTextView = [[UITextView alloc] init];
    titleTextView.frame = CGRectMake(0, 0, SCREEN_WIDTH-14, 1);
    titleTextView.textContainerInset = UIEdgeInsetsMake(21, 0, 21, 0);
    titleTextView.font = [UIFont boldSystemFontOfSize:24];
    titleTextView.text = self.albumTitle;
    self.titleCellHeight = [self heightForString:titleTextView  andWidth:SCREEN_WIDTH-14];
    
    if (self.titleCellHeight < kAlbumTitleHeight) {
        self.titleCellHeight = kAlbumTitleHeight ;
    }
    
    [titleTextView removeFromSuperview];
    titleTextView = nil;
    
    
    
    self.albumDesc = _dataSource.desc;
    
    UITextView *descTextView = [[UITextView alloc] init];
    descTextView.frame = CGRectMake(0, 0, SCREEN_WIDTH-14, 1);
    descTextView.textContainerInset = UIEdgeInsetsMake(28, 0, 28, 0);
//    descTextView.text = self.albumDesc;
    descTextView.font = kAlbumDescFont;
    [self textViewparagraphStyle:descTextView withText:self.albumDesc];
    [self.view addSubview:descTextView];
    self.descCellHeight = [self heightForString:descTextView  andWidth:SCREEN_WIDTH - 14];
    if (self.descCellHeight < kAlbumTitleHeight) {
        self.descCellHeight = kAlbumTitleHeight;
    }
    [descTextView removeFromSuperview];
    descTextView = nil;
    
    
    NSArray *privacyUserIDs = [album.privacyUserIDs componentsSeparatedByString:@","];
    
    for(NSInteger index = 0; index < privacyUserIDs.count; index++) {
        NSString *privacyUserID = [privacyUserIDs validStringAtIndex:index];
        
        if(privacyUserID.length > 0) {
            [_dataSource.privacyUserIDs addSafeObject:privacyUserID];
        }
    }
    
    NSArray <PPAlbumImageModel *> *images = [PPAlbumImageModel where:@{@"auuid" : auuid, @"deleted" : @(NO)}];
    
    NSArray <PPAlbumTagModel *> *tags = [PPAlbumTagModel where:@{@"auuid" : auuid}];
    
    [images enumerateObjectsUsingBlock:^(PPAlbumImageModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAbstractArtwork *artwork = obj.artwork;
        if(_dataSource.order.integerValue == PPAlbumOrderAsc){
        
            [_dataSource.images addObject:artwork];
              [self.pictures insertObject:artwork atIndex:0];
        }else{
            [_dataSource.images insertObject:artwork atIndex:0];
            
            [self.pictures addObject:artwork];
        }
        
       
        
    }];
    
    [tags enumerateObjectsUsingBlock:^(PPAlbumTagModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAlbumTagElement *tag = [[PPAlbumTagElement alloc] init];
        tag.tagID = obj.tagID;
        tag.name = obj.name;
        [_dataSource.tags addObject:tag];
    }];
    
    
    if (self.images.count > 0 && self.dataSource.images.count<=0) {
        for (UIImage *img in self.images) {
            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
            artwork.uuid = [NSString uuid];
            artwork.image = [img fixOrientation];
            artwork.created = YES;

            [_dataSource.images addObject:artwork];
            
            [_dataSource.insertedImages addObject:artwork];
            
             [self.pictures addObject:artwork];
        }
    }
    PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
    artwork.image = [UIImage imageNamed:@"pic_add"];
    artwork.isFlag =TRUE;
    

    
//    if(_dataSource.order.integerValue == PPAlbumOrderAsc) {
//         self.pictures = [[_dataSource.images.reverseObjectEnumerator allObjects] mutableCopy];;
//        [self.pictures insertObject:artwork atIndex:0];
//
//    } else {
//        [_dataSource.images addObject:artwork];
//        self.pictures = [_dataSource.images mutableCopy];
//    }
    
    if(_dataSource.order.integerValue == PPAlbumOrderAsc) {
        
        [_dataSource.images insertObject:artwork atIndex:0];
        
//        self.pictures = _dataSource.images;
        
        [self.pictures insertObject:artwork atIndex:0];
    } else {
        
        [_dataSource.images addObject:artwork];
//        [_dataSource.images insertObject:artwork atIndex:0];
//        self.pictures = [[_dataSource.images.reverseObjectEnumerator allObjects] copy];
//        self.pictures = self.dataSource.images;
        
        [self.pictures addObject:artwork];
    }
    
//    for (PPAbstractArtwork *Art in _dataSource.images) {
        
//        [self.pictures addObject:Art];
//    }
    
    self.isSort = [_dataSource.order integerValue];
    [self.tableView reloadData];

}

- (void)textViewparagraphStyle:(UITextView *)textView withText:(NSString *)text{

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = kAlbumDescSpace/2;// 字体的行间距
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName:textView.font,
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    textView.attributedText = [[NSAttributedString alloc] initWithString:text attributes:attributes];
    
}
#pragma mark - PPCreateAlbumTableViewAlbumCellDelegate

- (void)removeAlbumPicture:(PPAbstractArtwork *)artwork removeIndex:(NSInteger)index{
    if(artwork == nil || !artwork.uuid) {
        return;
    }
    
    [_dataSource.deletedImages addObject:artwork];
    [_dataSource.modifiedImages removeObject:artwork];
    [_dataSource.insertedImages removeObject:artwork];
    
    [_dataSource.images removeObject:artwork];
    
    [self.pictures removeObject:artwork];
    
    NSIndexPath *indexP =[NSIndexPath indexPathForRow:2 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexP] withRowAnimation:UITableViewRowAnimationNone];
    

}

- (void)didSelectAlbumPicture:(PPAbstractArtwork *)artwork selectIndex:(NSInteger)selectIndex {
    
    if(artwork == nil) {
        return;
    }
    
    NSMutableArray *sortedImages = [NSMutableArray array];
    
    for (int i=0; i<self.pictures.count; i++) {
        PPAbstractArtwork *tempArtwork = self.pictures[i];
        if (tempArtwork.uuid) {
            [sortedImages addObject:tempArtwork];
        }

    }
    
    
    PPAlbumContentPictureViewController *pictureViewController = [[PPAlbumContentPictureViewController alloc] init];
    pictureViewController.artworks = sortedImages;
    
    pictureViewController.index = _dataSource.order.integerValue ==0?selectIndex-1:selectIndex;
    pictureViewController.view.backgroundColor = WHITE;
    pictureViewController.delegate = self;
    [self.navigationController pushViewController:pictureViewController animated:YES];
}

- (void)addAlbumPicture{

    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:50 delegate:self];
    imagePickerVc.naviBgColor = WHITE;
    imagePickerVc.naviTitleColor = BLACK;
    imagePickerVc.naviTitleFont = PPFONT(@"Helvetica-Bold", 17);
    imagePickerVc.barItemTextColor = BLACK;
    imagePickerVc.barItemTextFont = PPFONTSIZE(16);
    imagePickerVc.allowPickingVideo = NO;
    WEAKSELF
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        
        for (UIImage *img in photos) {
            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
            artwork.uuid = [NSString uuid];
            artwork.image = [img fixOrientation];
            artwork.created = YES;
            
            if (artwork.uuid) {
                if(_dataSource.order.integerValue == PPAlbumOrderDesc){
                    [self.pictures insertObject:artwork atIndex:self.pictures.count-1];
                    
                    [self.dataSource.insertedImages addObject:artwork];
                    [self.dataSource.images insertObject:artwork atIndex:self.dataSource.images.count-1];
                }else{
                    //倒序
                    if (self.pictures.count >1) {
                        [self.pictures insertObject:artwork atIndex:1];
//                        [self.dataSource.images insertObject:artwork atIndex:1];
//                        [self.dataSource.insertedImages insertObject:artwork atIndex:0];
                    }else{
                        [self.pictures addObject:artwork];
//                        [self.dataSource.images addObject:artwork];
                    }
                    [self.dataSource.images addObject:artwork];
                    [self.dataSource.insertedImages insertObject:artwork atIndex:0];
                }
            }
            
            
        }

//        [weakSelf.tableView reloadData];
        
        NSIndexPath *indexP = [NSIndexPath indexPathForRow:2 inSection:0];
        
        [weakSelf.tableView reloadRowsAtIndexPaths:@[indexP] withRowAnimation:UITableViewRowAnimationNone];
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - PPAlbumContentPictureViewControllerDelegate

- (void)pictureViewController:(PPAlbumContentPictureViewController *)pictureViewController setArtworkAsCover:(PPAbstractArtwork *)artwork {
    self.dataSource.coverUUID = artwork.uuid;
}

- (void)pictureViewController:(PPAlbumContentPictureViewController *)pictureViewController setDescription:(NSString *)description forArtwork:(PPAbstractArtwork *)artwork {
    artwork.desc = description;
    
    if(![self.dataSource.modifiedImages containsObject:artwork]) {
        [self.dataSource.modifiedImages addObject:artwork];
    }
}

- (void)keyboardWillShow:(NSNotification *)notification{
    
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.keboardHeight = keyboardFrame.origin.y;
    
    NSTimeInterval animalInterval = [[[notification userInfo]objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    self.animalInterval = animalInterval;
    
}


-(void)keyboardWillHide:(NSNotification *)aNotification
{
//    NSTimeInterval animalInterval=[[[aNotification userInfo]objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//    NSIndexPath *indexP = [NSIndexPath indexPathForRow:3 inSection:0];
//    PPAlbumSortCell *cell = [self.tableView cellForRowAtIndexPath:indexP];

//    [UIView animateWithDuration:animalInterval animations:^{
 
//        CGRect viewF = self.tableView.frame;
//        viewF.origin.y = 0;
//        viewF.size.height = SCREEN_HEIGHT-64;
////        viewF = self.view.bounds;
//        self.tableView.frame = viewF;
//    }];
}
- (void)didReceiveMemoryWarning{
    
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] cleanDisk];
    [[SDWebImageManager sharedManager] cancelAll];

    PPLog(@"内存警告啦！");
}

@end
